package main

import (
	"relay-control/lib/serial"
	"relay-control/lib/utils"
	"relay-control/src/basic/base"
	"relay-control/src/machine/listener"
	"relay-control/src/machine/mvc"
	"relay-control/src/machine/properties"
	"relay-control/src/web"
	"time"
)

// main
func main() {

	Run()

	for {
		time.Sleep(1 * time.Second)
	}
}

//Run 初始化
func Run() {
	base.Logger.Info().Println(" -- starting init")
	base.Logger.Info().Println(" -- read properties.json")
	initJsonConfig()
	loadOptions()
	base.Logger.Info().Println(" -- init serial port")
	initSerialPort()
	base.Logger.Info().Println(" -- init mvc")
	initMvc()
	base.Logger.Info().Println(" -- init succeed")
}

// initJsonConfig NO.1 initialize
// 初始化JsonConfig
func initJsonConfig() {
	properties.ReadConfigJson()
}

// loadOptions NO.2 转存储options
func loadOptions() {
	options := properties.Properties.PortOptions
	for i := range options {
		base.Options = append(base.Options, options[i])
	}
}

//initSerialPort NO.3 initialize
//初始化串口并监听
func initSerialPort() {
	for i := range base.Options {
		openAndStartListen(base.Options[i])
	}
}

func openAndStartListen(options serial.OpenOptions) {
	portRW := utils.OpenSerialPort(options)
	base.SerialPortMap[options.PortName] = portRW
	go listener.ListenPort(options.PortName)
}

//initMvc NO.4
func initMvc() {
	web.InitController()
	go mvc.ListenHttp()
}
